package com.fingard.dsp.bank.directbank.dbs01;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.ITransaction;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7515TodayTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7516HisTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.RetAtsTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.detail.RetAtsTransDetail;
import com.fingard.io.FileHelper;
import com.fingard.util.DateHelper;
import com.alibaba.fastjson.JSONObject;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.Calendar;
import java.util.Date;

/**
 * Created by F on 2018/7/13.
 */
public class DBS01Transaction extends DBS01Base implements ITransaction {
    @Override
    public RetAtsTrans d_7516_HisTrans(Req7516HisTrans p_req7516) throws Exception {
        return "1".equals(getBankConfig().getValueAsString("channelFlag"))?d_7516_HisTransByAPI(p_req7516):d_7516_HisTransByFile(p_req7516);
    }

    //API方式
    public RetAtsTrans d_7516_HisTransByAPI(Req7516HisTrans p_req7516) throws Exception {
        RetAtsTrans retAts = new RetAtsTrans(p_req7516.reqHeader);
        retAts.writeStart();//写返回ATS的统一头部信息
        try {
            Calendar tmpCalendarFrom = Calendar.getInstance();
            tmpCalendarFrom.setTime(p_req7516.getDateFrom());

            Calendar tmpCalendarTo = Calendar.getInstance();
            tmpCalendarTo.setTime(p_req7516.getDateTo());

            int tmpIntDateFrom = 0;
            int tmpIntDateTo = 0;
            //按自然月循环查询
            while(tmpIntDateFrom<=tmpIntDateTo){
                Calendar tmpClndrStepTo = Calendar.getInstance();
                tmpClndrStepTo.setTime(tmpCalendarFrom.getTime());
                //判断是否跨月
                if(DateHelper.compareMonth(tmpCalendarFrom, tmpCalendarTo) == -1){
                    //跨月则设置为月末
                    tmpClndrStepTo.set(Calendar.DAY_OF_MONTH, tmpClndrStepTo.getActualMaximum(Calendar.DAY_OF_MONTH));
                }
                else{
                    tmpClndrStepTo.setTime(tmpCalendarTo.getTime());
                }

                String fromDate = Format.Date8Format.format(tmpCalendarFrom.getTime());
                String toDate = Format.Date8Format.format(tmpClndrStepTo.getTime());
                String date=Format.DateTimeSSSFormat.format(new Date());//yyyy-MM-dd HH:mm:ss SSS
                StringBuilder sb2=new StringBuilder(date.replaceAll(" ",""));
                sb2.insert(10,"T").insert(19,".");
                JSONObject header = new JSONObject();
                header.put("msgId", getQryTransID());//流水号
                header.put("orgId", bankFront.org);//机构号
                header.put("timeStamp", sb2.toString());//时间 yyyy-MM-ddTHH:mm:ss.SSS
                header.put("ctry", getBankConfig().getMapKeyByValue("cityFlag",p_req7516.actNum));//Country triggering the JSON
                JSONObject accInfo = new JSONObject();
                accInfo.put("accountNo",p_req7516.actNum);
                accInfo.put("accountCcy",convertCurToBank(p_req7516.actCur));
                accInfo.put("fromDate",fromDate);
                accInfo.put("toDate",toDate);
                accInfo.put("drCrInd","ALL");
                accInfo.put("noTxnInd","");//查询数目
                accInfo.put("chronoFlag","");
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("header",header);
                jsonObject.put("accInfo",accInfo);

                //发送请求报文
                String[] bankResult = sendToBank(jsonObject.toString(),"enquiry/v1/account/range");
//                String[] bankResult = new String[]{"",FileHelper.readFileText("D:\\开发文档\\星展银行\\API技术文档\\ARE sample.TXT","UTF-8")};
                //处理响应报文
                if (bankResult[0].length() == 0) {
                    JSONObject json = JSONObject.parseObject(bankResult[1].replaceAll(" ",""));
                    if(!"".equals(json.getString("txnEnqResponse")) && json.getString("txnEnqResponse")!=null){
                        JSONObject object=(JSONObject)json.get("txnEnqResponse");
                        if("ACSP".equals(object.get("enqStatus"))){//查询成功
                            JSONArray acctInfo = JSON.parseArray(object.getString("acctInfo"));
                            for (int i = 0; i < acctInfo.size(); i++){
                                JSONObject infoJSONObject = acctInfo.getJSONObject(i);
                                String availableBal = infoJSONObject.getString("availableBal");
                                availableBal = availableBal.substring(0,availableBal.lastIndexOf(".")+5);
                                JSONArray initiatingParty = JSON.parseArray(infoJSONObject.getString("initiatingParty"));
                                for (int j = 0; j < initiatingParty.size(); j++){
                                    JSONObject transDetail = initiatingParty.getJSONObject(i);
                                    String oppoName = transDetail.getString("name");
                                    JSONArray txnInfo = JSON.parseArray(transDetail.getString("txnInfo"));
                                    for (int k = 0; k < txnInfo.size(); k++){
                                        JSONObject detail = txnInfo.getJSONObject(i);
                                        RetAtsTransDetail tmpRetDetail = new RetAtsTransDetail();
                                        tmpRetDetail.actNum = p_req7516.actNum;
                                        tmpRetDetail.cur =  convertCurToATS(detail.getString("txnCcy"));
                                        tmpRetDetail.tranAmt = Format.DecimalAmtFormat.format(Double.parseDouble(detail.getString("txnAmount")));
                                        //交易日期
                                        String dealDate = detail.getString("txnDate");
                                        if(dealDate.length() <= 8){
                                            tmpRetDetail.tranDate = dealDate.substring(0, 4) + "-" + dealDate.substring(4, 6) + "-" + dealDate.substring(6, 8);
                                        }else{
                                            tmpRetDetail.tranDate = dealDate.substring(0, 10);
                                        }
                                        //起息日
                                        String valueDate = detail.getString("txnDate");
                                        if(valueDate.length() <= 8){
                                            tmpRetDetail.valueDate = valueDate.substring(0, 4) + "-" + valueDate.substring(4, 6) + "-" + valueDate.substring(6, 8);
                                        }else{
                                            tmpRetDetail.valueDate = valueDate.substring(0, 10);
                                        }
                                        tmpRetDetail.tranTime = tmpRetDetail.tranDate + " 00:00:00";
                                        tmpRetDetail.postTimestamp = tmpRetDetail.tranTime;
                                        tmpRetDetail.recAccNum = "";
                                        tmpRetDetail.recAccName = oppoName;
                                        tmpRetDetail.accBal = Format.DecimalAmtFormat.format(Double.parseDouble(availableBal));
                                        tmpRetDetail.usage = detail.getString("txnDesc");
                                        tmpRetDetail.comment = tmpRetDetail.usage;
                                        retAts.writeRetDetail(tmpRetDetail);
                                    }
                                }
                            }
                        }else {
                            WriteBankLogLn("查询"+fromDate+"-"+toDate+"失败，"+object.get("enqStatusDescription").toString());
                            break;
                        }
                    }else {
                        WriteBankLogLn("查询"+fromDate+"-"+toDate+"失败，返回txnEnqResponse不存在");
                        break;
                    }
                }else {
                    WriteBankLogLn("查询"+fromDate+"-"+toDate+"失败，原因："+bankResult[1]);
                    break;
                }

                tmpCalendarFrom = tmpClndrStepTo;
                tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);
                tmpIntDateFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
                tmpIntDateTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));
            }
        }catch (Exception ex) {
            ex.printStackTrace();
            WriteBankLogLn(ex);
        }
        retAts.writeEnd();
        return retAts;
    }

    public RetAtsTrans d_7516_HisTransByFile(Req7516HisTrans p_req7516) throws Exception {
        RetAtsTrans retAts = new RetAtsTrans(p_req7516.reqHeader);
        retAts.writeStart();//写返回ATS的统一头部信息
        String accountNum = p_req7516.actNum;
        Date dateStart = Format.Date8Format.parse(p_req7516.dateFrom);
        Date dateEnd = Format.Date8Format.parse(p_req7516.dateTo);
        Calendar calendar = Calendar.getInstance();
        while (!dateStart.after(dateEnd)){
            String dealedPath = getBankConfig().getValueAsString("DealedPath")+File.separator+
                    Format.Date8Format.format(dateStart)+File.separator+"MT940"+File.separator+
                    accountNum+"_7516.txt";
            if(!FileHelper.existFile(dealedPath)){
                calendar.setTime(dateStart);
                calendar.add(Calendar.DAY_OF_MONTH, 1);
                dateStart = calendar.getTime();
                continue;
            }
            String readLine = "";
            InputStreamReader isr = null;
            FileInputStream fis = null;
            BufferedReader reader = null;
            try {
                fis = new FileInputStream(dealedPath);
                isr = new InputStreamReader(fis, "UTF-8");
                reader = new BufferedReader(isr);
            } catch (Exception e) {
                System.out.println(e.getMessage());
            } finally {
                if (reader != null) {
                    reader.close();
                }
                if (isr != null) {
                    isr.close();
                }
                if (fis != null) {
                    fis.close();
                }
            }
            while ((readLine=reader.readLine())!=null) {
                //    账号 | 币种 | 交易日期| 交易时间| 计息日期 | 交易金额 |借贷标识| 账户余额 |对方账号|
//                    对方户名 | 对方银行 |用途
                String[] transDetail = readLine.split("\\|");
                RetAtsTransDetail retDetail = new RetAtsTransDetail();
                retDetail.actNum = transDetail[0];
                retDetail.cur =convertCurToATS(transDetail[1]);
                retDetail.tranDate = transDetail[2];
                retDetail.tranTime = transDetail[3];
                retDetail.valueDate = transDetail[4];
                retDetail.tranAmt = transDetail[5];
                retDetail.cdFlag = "C".equals(transDetail[6])?"2":"1";
                retDetail.accBal = transDetail[7];
                retDetail.recAccNum = transDetail[8];
                retDetail.recAccName = transDetail[9];
                retDetail.recAccBank = transDetail[10];
                if(!"没有获取支付说明".equals(transDetail[11])){
                    retDetail.usage = transDetail[11];
                }
                retAts.writeRetDetail(retDetail);
            }
            reader.close();
            calendar.setTime(dateStart);
            calendar.add(Calendar.DAY_OF_MONTH, 1);
            dateStart = calendar.getTime();
        }
        retAts.writeEnd();
        return retAts;
    }

    public RetAtsTrans d_7515_TodayTransByFile(Req7515TodayTrans p_req7515) throws Exception {
        RetAtsTrans retAts = new RetAtsTrans(p_req7515.reqHeader);
        retAts.writeStart();
        String accNum = p_req7515.actNum;
        String date =Format.Date8Format.format(new Date());
        String dealedPath = getBankConfig().getValueAsString("DealedPath")+File.separator+date+
                File.separator+"MT942"+File.separator+accNum+"_7515.txt";
        if(FileHelper.existFile(dealedPath)){
            InputStreamReader isr = null;
            FileInputStream fis = null;
            BufferedReader reader = null;
            try {
                fis = new FileInputStream(dealedPath);
                isr = new InputStreamReader(fis, "UTF-8");
                reader = new BufferedReader(isr);
            } catch (Exception e) {
                System.out.println(e.getMessage());
            } finally {
                if (reader != null) {
                    reader.close();
                }
                if (isr != null) {
                    isr.close();
                }
                if (fis != null) {
                    fis.close();
                }
            }
            String readLine ="";
            while ((readLine=reader.readLine())!=null){
                // 账号 | 币种 | 交易日期| 交易时间| 计息日期 | 交易金额 |借贷标识| 账户余额 |对方账号|
                // 对方户名 | 对方银行 |用途
                String[] transDetail = readLine.split("\\|");
                RetAtsTransDetail detail = new RetAtsTransDetail();
                detail.actNum = transDetail[0];
                detail.cur =convertCurToATS(transDetail[1]);
                detail.tranDate =transDetail[2];
                detail.tranTime = transDetail[3];
                detail.valueDate = transDetail[4];
                detail.tranAmt = transDetail[5];
                detail.cdFlag = "C".equals(transDetail[6])?"2":"1";
                detail.accBal =transDetail[7];
                detail.recAccNum =transDetail[8];
                detail.recAccName = transDetail[9];
                detail.recAccBank = transDetail[10];
                if(!"没有获取支付说明".equals(transDetail[11])){
                    detail.usage = transDetail[11];
                }
                retAts.writeRetDetail(detail);
            }
        }else{
            retAts.writeRespCode("0");
            retAts.writeRespInfo("今日明细银行还没返回,请稍后再查");
        }
        retAts.writeEnd();
        return retAts;
    }

    @Override
    public RetAtsTrans d_7515_TodayTrans(Req7515TodayTrans p_req7515) throws Exception {
        if("1".equals(getBankConfig().getValueAsString("channelFlag"))){
            //通用历史明细查询
            Req7516HisTrans tmpReq7516 = new Req7516HisTrans(p_req7515.reqHeader);
            tmpReq7516.actArea = p_req7515.actArea;
            tmpReq7516.actCur = p_req7515.actCur;
            tmpReq7516.actNum = p_req7515.actNum;
            String tmpStrToday = Format.Date8Format.format(new Date());
            tmpReq7516.dateFrom = tmpStrToday;
            tmpReq7516.dateTo = tmpStrToday;
            return 	d_7516_HisTransByAPI(tmpReq7516);
        }else{
            return d_7515_TodayTransByFile(p_req7515);
        }
    }
}
